from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
import re
# Create your views here.
class LoginView(APIView):
    def post(self,request):
        mobile = request.data.get('mobile')
        pwd = request.data.get('pwd')
        if not all([mobile,pwd]):
            return Response({'msg':'参数不完整','code':400})
        if not re.findall(r'^1[3-9]\d{9}$',mobile):
            return Response({'msg':'手机号格式错误','code':400})
        # t_pwd = UserModel.objects.get(password=pwd)
        # if pwd != t_pwd:
        #     return Response({'msg':'密码错误','code':400})
        try:
            UserModel.objects.get(mobile=mobile,password=pwd)
            return Response({'msg':'登录成功','code':200})
        except Exception as e:
            print(e)
            UserModel.objects.create(mobile=mobile,password=pwd)
            return Response({'msg':'登录注册成功','code':201})

class AddrView(APIView):
    def get(self,request,id):
        user = UserModel.objects.get(id=id)
        try:
            t_user = AddrModel.objects.filter(user_id=user)
        except Exception as e:
            print(e)
            return Response({'msg':'获取地址失败','code':400})
        lst = []
        for i in t_user:
            lst.append({
                'name':i.name,
                'mobile':i.mobile,
                'addr':i.addr
            })
        return Response({'msg':'获取成功','code':200})
    def post(self,request):
        name = request.data.get('name')
        mobile = request.data.get('mobile')
        addr = request.data.get('addr')
        if not all([name,mobile,addr]):
            return Response({'msg':'参数不完整','code':400})
        try:
            AddrModel.objects.create(name=name,mobile=mobile,addr=addr)
        except Exception as e:
            print(e)
            return Response({'msg':'添加地址失败','code':401})
        return Response({'msg':'添加成功','code':200})



class AddrUpView(APIView):
    def put(self,request,id):
        name = request.data.get('name')
        mobile = request.data.get('mobile')
        addr = request.data.get('addr')
        if not all([name,mobile,addr]):
            return Response({'msg':'参数不完整','code':400})
        try:
            AddrModel.objects.filter(id=id).update(name=name,mobile=mobile,addr=addr)
        except Exception as e:
            print(e)
            return Response({'msg':'编辑失败','code':400})
        return Response({'msg':'编辑成功','code':200})


class DelAddrView(APIView):
    def delete(self,request,id):
        AddrModel.objects.filter(id=id).delete()
        return Response({'msg': '删除成功', 'code': 200})




